import {defineStore} from "pinia";
import { useRouter } from "vue-router";

export const useNavStore = defineStore("navItems", {
    state: () => ({
        navItems: [],
        collapse: false,
    }),

    actions: {
        toggleCollapse() {
            this.collapse = !this.collapse;
        },

        /**
         * Add a nav item
         * @param {router} item
         */
        addNavItem(item) {
            // Add a new item to the navItems array
            // This will be used to dynamically add items to the sidebar
            // if navItems does not include item, add it
            // item is an object with the following properties: { path, name, icon }, path is required and unique

            // get the optional path array from navItems
            const paths = this.navItems.map((i) => i.path);
            if (paths.includes(item.path)) return;
            this.navItems.push(item);
        },
        /**
         * Remove a nav item
         * @param {router} item
         */
        removeNavItem(item) {

            // 从navItems数组中删除项目
            const paths = this.navItems.map((i) => i.path);
            if (!paths.includes(item.path)) return false;

            // get the previous nav item from the navItems array before removing the item
            let index = paths.indexOf(item.path);
            let target = null;
            if (index === 0) {
                target = this.navItems[index + 1];
            } else {
                target = this.navItems[index - 1];
            }

            // filter out the item
            this.navItems = this.navItems.filter((i) => i.path !== item.path);

            return target;
        },
    },
});
